package top.rainbowecho.ai.domain.model.robot.strategy.impl;

import org.springframework.stereotype.Component;
import top.rainbowecho.ai.domain.model.robot.strategy.SensitiveTextRecognizeStrategy;
import top.rainbowecho.ai.domain.model.robot.value.text.BaiduCheckResult;
import top.rainbowecho.ai.domain.model.robot.value.text.Reject;
import top.rainbowecho.common.domain.shared.vo.SensitiveRecognizeResult;
import top.rainbowecho.common.util.ExceptionMessageContent;

import java.util.*;

import static cn.hutool.core.collection.CollUtil.isNotEmpty;

/**
 * @author rainbow
 * @since 2019/11/29 15:23
 */
@Component
public class SensitiveTextRecognizeStrategyImpl implements SensitiveTextRecognizeStrategy {
    private static final Map<Integer, String> LABEL_MAP = new HashMap<>(8);

    static {
        LABEL_MAP.put(1, "色情文本");
        LABEL_MAP.put(2, "政治敏感");
        LABEL_MAP.put(3, "恶意推广");
        LABEL_MAP.put(4, "网络暴恐");
        LABEL_MAP.put(5, "低俗辱骂");
    }

    /**
     * 对百度AI接口的响应结果进行识别
     *
     * @param reply AI接口响应结果
     * @return 识别的结果
     */
    @Override
    public SensitiveRecognizeResult recognize(BaiduCheckResult reply) {
        List<Reject> rejects = reply.getResult().getReject();
        String label;
        boolean sensitive = isNotEmpty(rejects);
        if (sensitive) {
            Optional<Reject> maxScoreItem = rejects.stream().max(Comparator.comparingDouble(Reject::getScore));

            int labelInt = Objects.requireNonNull(maxScoreItem.orElse(null)).getLabel();
            label = LABEL_MAP.get(labelInt);
        } else {
            label = ExceptionMessageContent.NORMAL;
        }
        return new SensitiveRecognizeResult(sensitive, label);
    }
}
